const { ccclass, property } = cc._decorator;
@ccclass
export default class TraceBulletControl extends cc.Component {
    /**
     *  子弹速度
     */
    @property(cc.Integer)
    BulletSpeed: number = 100;

    /**
     *  目标节点
     */
    private mTargetNode: cc.Node = null;
    public get TargetNode(): cc.Node {
        return this.mTargetNode;
    }

    /**
     *  是否暂停
     */
    private mIsPause: boolean = false;
    public set IsPause(value: boolean) {
        this.mIsPause = value;
    }
    public get IsPause(): boolean {
        return this.mIsPause;
    }

    public bindTarget(target: cc.Node): void {
        this.stop();
        this.mTargetNode = target;
        this.mIsPause = false;
        this.schedule(this.updateTrace, 0.01);
    }

    public stop(): void {
        this.mTargetNode = null;
        this.mIsPause = true;
        this.unschedule(this.updateTrace);
    }

    public updateTrace(dt: number): void {
        if (this.mIsPause || !this.mTargetNode)
            return;
        let targetPos = this.mTargetNode.getPosition().clone();
        let bulletPos = this.node.getPosition().clone();

        let normalizeVec2 = targetPos.subtract(bulletPos).normalize();
        this.node.x += normalizeVec2.x * this.BulletSpeed * dt;
        this.node.y += normalizeVec2.y * this.BulletSpeed * dt;
        this.node.angle = cc.v2(0, 1).signAngle(normalizeVec2) * 180 / Math.PI;
    }
}
